﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MUD.Lib.Objects.Domains;
using MUD.Lib.Utils;
using MUD.Lib.Objects.Users;
using MUD.Lib.Utils;

namespace MUD.Lib.Objects.Rooms
{
    internal class Exit
    {
        public Type AbstractType;
        public object Reference;
        public string ID;

        public Exit(string pID, Type typeInfo)
        {
            AbstractType = typeInfo;
            // TODO: Need some sort of type-assurance here to make sure this type is a child of "Room"
            if (!AbstractType.IsSubclassOf(Type.GetType("MUD.Lib.Objects.Rooms.Room")))
                throw new Exception("Exit defined is not a subclass of room and thus cannot hold characters!");

            ID = pID;
        }

        public void Initialize(Domain domain, Room fromRoom)
        {
            if ((Reference = domain[AbstractType]) == null)
            {
                Reference = Activator.CreateInstance(AbstractType, new object[] {domain});
                domain[AbstractType] = (Room)Reference;
            }
            fromRoom.AddVerb(ID, new VerbProcessor.CommandHandler(ExitHandler));
        }

        private bool ExitHandler(User user, string command)
        {
            // if the user entered the movement command for this exit, move 'em.
            if (command.NthWord(0).ToLower() == ID.ToLower())
            {
                try
                {
                    user.Move((Room)Reference);
                    return true;
                }
                catch (Exception ex)
                {
                    Log.LogMessage(ex.Message);
                }
            }
            return false;
        }
    }
}
